<template>
    <div class="page-question">
        <vue-scroll :pullDownRefresh="false" :pullUpLoad="false" class="wc-question" ref="scroll">
            <div style="overflow: hidden;">
                <div class="question-desc">
                    <!-- <div>1、填写表单</div>
                    <div>2、邀请好友测试彼此好感指数</div>
                    <div>3、发现和陌生人的未知缘分 </div> -->
                    <!-- <div>4、一次数据填写，结果持续更新</div> -->
                    一次数据填写，结果持续更新
                </div>
                <template v-for="item in dList" v-if="dList.length">
                    <template v-if="item.formType == 1">
                        <mt-radio
                            class="question_item"
                            :class="{'question_item_required': item.required}"
                            :title="`${item.id}、${item.questionTitle}`"
                            v-model="dValue[item.id]"
                            :options="item.options.map(opt => opt.optionContent)">
                        </mt-radio>
                    </template>
                    <template v-if="item.formType == 3">
                        <template v-if="item.multiple">
                            <div class="question_item mint-field">
                                <div class="mint-cell-wrapper">
                                    <div class="mint-cell-title">
                                        <span class="mint-cell-text">{{`${item.id}、${item.questionTitle}`}}</span>
                                    </div>
                                    <ul class="tag-list">
                                        <li class="tag-item" :class="{'tag-item_active': dValue[item.id].indexOf(tag.optionContent) > -1}" v-for="tag in item.options" @click="_choose(tag, item)">{{tag.optionContent}}</li>
                                    </ul>
                                </div>
                            </div>
                        </template>
                        <mt-radio
                            class="question_item"
                            :class="{'question_item_required': item.required}"
                            v-else
                            :title="`${item.id}、${item.questionTitle}`"
                            v-model="dValue[item.id]"
                            :options="item.options.map(opt => opt.optionContent)">
                        </mt-radio>
                    </template>
                    <template v-else-if="item.formType == 2">
                        <mt-field class="question_item" :class="{'question_item_required': item.required}" :label="`${item.id}、${item.questionTitle}`" placeholder="请输入" v-model="dValue[item.id]"></mt-field>
                    </template>
                    <template v-else-if="item.formType == 5">
                        <div class="question_item mint-field">
                            <div class="mint-cell-wrapper">
                                <div class="mint-cell-title">
                                    <span class="mint-cell-text">{{`${item.id}、${item.questionTitle}`}}</span>
                                </div>
                                <div class="field-cpcd" @click="_selectCpcd">
                                    <mt-field class="question_item" :class="{'question_item_required': item.required}" placeholder="请选择" v-model="dValue[item.id]" :disabled="true"></mt-field>
                                    <i class="mint-cell-allow-right"></i>
                                </div>
                            </div>
                        </div>
                    </template>
                </template>
                <div class="btn-wrap">
                    <div class="btn" v-if="dPage !== 0" @click="--dPage">上一页</div>
                    <div class="btn" v-if="dPage !== 5" @click="++dPage">下一页</div>
                    <div class="btn" v-if="dPage == 5" @click="submit">提交</div>
                </div>
                <div class="btn" @click="$router.push('/matchactivity/find')">测试查看发现</div>
            </div>
        </vue-scroll>
        <mt-popup
          v-model="dPopup"
          position="bottom"
          style="width: 100%;">
            <mt-picker :slots="slots" @change="onValuesChange"></mt-picker>
        </mt-popup>
    </div>
</template>
<script type="text/javascript">
    import axios from 'axios'
    import util from '@/common/util'
    import cpcd from './cpcd'
    export default {
        data () {
            return {
                dValue: {},
                dPage: -1,
                dList: [],
                dPopup: false,
                slots: []
            }
        },
        watch: {
            dValue: {
                deep: true,
                handler (val) {
                    this.saveStorage(val);
                }
            },
            dPage (val) {
                this.dList = this.list.slice(val * 5, (val+1) * 5);
            }
        },
        created () {
            var savedValue = window.localStorage.getItem('value');
            if (savedValue) {
                this.dValue = JSON.parse(savedValue);
            }
            this.slots = this._parseCpcd();
            this._fetch();
        },
        methods: {
            _fetch () {
                let list = [];
                const { dValue } = this;
                axios.get('/api/java/question/list').then((res) => {
                    if (res.data.code == 0) {
                        res.data.data.forEach((item) => {
                            if (!dValue[item.id] || !dValue[item.id].length) {
                                dValue[item.id] = item.formType == 3 && item.multiple ? [] : '';
                            }
                            list.push(item);
                        });
                        this.list = list;
                        this.dPage = 0;
                        this.$refs.scroll && this.$refs.scroll.forceUpdate();
                    }
                })
            },
            saveStorage (val) {
                window.localStorage && window.localStorage.setItem('value', JSON.stringify(val));
            },
            submit () {
                var result = [];
                const { dValue } = this;
                var tip = this.getTip();
                if (tip) {
                    util.toast(tip);
                    return;
                }
                Object.keys(dValue).forEach((id) => {
                    const val = dValue[id];
                    console.log(val);
                    if (typeof val === 'string') {
                        result.push({
                            questionId: id,
                            answer: val && /$[A-Z]\./.test(val) ? val.chatAt(0) : val
                        });
                    }else{
                        result.push({
                            questionId: id,
                            answer: val
                        });
                    }
                })
                axios.post('/api/java/question/answer/submit', {
                    openid: window.app.openId,
                    answers: result
                }).then((res) => {
                    if (res.code === 0) {
                        alert('您已提交！');
                        window.localStorage && window.localStorage.setItem('value', '');
                        this.$router.push('index1');
                    }
                });
            },

            getTip () {
                const { dValue } = this;
                let tip = '';
                this.dList.some((item) => {
                    if (item.required) {
                        if (item.formType == 3 && item.multiple) {
                            if (!dValue[item.id].length) {
                                tip = `第${item.id}道题`;
                                return true;
                            }
                        }else{
                            if (!dValue[item.id]) {
                                tip = `第${item.id}道题`;
                                return true;
                            }
                        }
                    }
                })
                return tip ? `请输入${tip}` : '';
            },

            _choose (tag,item) {
                var value = this.dValue[item.id];
                var index = value.indexOf(tag.optionContent);
                if (index === -1) {
                    if (value.length == 5) {
                        return;
                    }
                    value.push(tag.optionContent);
                }else{
                    value.splice(index, 1)
                }
                this.saveStorage(this.dValue);
                this.$forceUpdate();
            },

            _selectCpcd () {
                this.dPopup = !this.dPopup;
            },

            _parseCpcd () {
                let value = this.dValue[28] ? this.dValue[28] : [];
                if (!this.city) {
                    this.city = {};
                    this.cityName = {};
                    this.province = {};
                    this.provinceName = {};
                    this.district = {};
                    this.districtName = {};
                    cpcd.province.options.map((item) => {
                        this.province[item.value] = item;
                        this.provinceName[item.label] = item;
                    })
                    cpcd.city.options.map((item) => {
                        this.city[item.value] = item;
                        this.cityName[item.label] = item;
                    })
                    cpcd.district.options.map((item) => {
                        this.district[item.value] = item;
                        this.districtName[item.label] = item;
                    })
                }
                let province = cpcd.province.options.map(item => item.label);
                let city = this._getCity(value[0] || province[0]);
                let district = this._getDistrict(value[1] || city[0]);
                return [{
                    flex: 1,
                    values: province,
                    className: 'slot1',
                    textAlign: 'center',
                    defaultIndex: province.indexOf(value[0])==-1?0:province.indexOf(value[0])
                }, {
                    flex: 1,
                    values: city,
                    className: 'slot2',
                    textAlign: 'center',
                    defaultIndex: city.indexOf(value[1])==-1?0:city.indexOf(value[1])
                }, {
                    flex: 1,
                    values: district,
                    className: 'slot3',
                    textAlign: 'center',
                    defaultIndex: district.indexOf(value[2])==-1?0:district.indexOf(value[2])
                }]
            },

            onValuesChange(picker, values) {
                const oldVal = this.dValue[28];
                if (oldVal[0] !== values[0]) {
                    const city = this._getCity(values[0]);
                    picker.setSlotValues(1, city);
                    picker.setSlotValues(2, this._getDistrict(city[0]));
                }else if(oldVal[1] !== values[1]){
                    picker.setSlotValues(2, this._getDistrict(values[1]));
                }
                this.dValue[28] = JSON.parse(JSON.stringify(values));
                this.saveStorage(this.dValue);
            },

            _getCity (provice) {
                return this.provinceName[provice].child_options[0].city.map((val) => {
                    return this.city[val].label
                })
            },

            _getDistrict (city) {
                return this.cityName[city].child_options[0].district.map((val) => {
                    return this.district[val].label
                })
            }
        }
    }
</script>
<style lang="less">
    .wc-question {
        padding: 0 23px;
        .question-desc {
            padding: 15px 0 30px;
            font-size: 15px;
            color: #0D0D0D;
            line-height: 24px;
            text-align: center;
        }
        .question_item {
            margin-bottom: 15px;
            .mint-checklist-title,
            .mint-cell-title,
            .mint-radiolist-title {
                width: auto;
                font-size: 16px;
                color: #0D0D0D;
                margin: 0 0 15px;
                line-height: 24px;
            }
            .mint-cell-wrapper {
                font-size: 16px;
                background: none;
                padding: 0;
                display: block;
            }
            .mint-cell {
                background: none;
                min-height: 22px;
            }
        }
        .mint-field-core {
            border-bottom: 1px solid #848282;
        }
    }
    .page-question {
        height: 100%;
    }
    .btn-wrap {
        display: flex;
    }
    .btn {
        margin: 0 auto 20px;
        font-size: 16px;
        line-height: 36px;
        height: 36px;
        background-color: #E3E3E3;
        width: 135px;
        color: #0D0D0D;
        text-align: center;
    }
    .question_item_required {
        .mint-radiolist-title:before {
            content: '* ';
            color: red;
        }
    }
    .tag-item {
        display: inline-block;
        line-height: 32px;
        padding: 0 10px;
        border: 1px solid #666;
        color: #666;
        margin: 0 12px 10px 0;
        border-radius: 32px;
    }
    .tag-item_active {
        color: #03a9f4;
        border-color: #03a9f4;
    }
    .field-cpcd {
        position: relative;
        .mint-cell-allow-right {
            position: absolute;
            right: -17px;
            top: 14px;
        }
    }
</style>
